<template>
  <div class="cont">
    <el-dialog
      title="登录"
      :model-value="true"
      :close-on-click-modal="false"
      width="300px"
      custom-class="con-dialog"
    >
      <el-form ref="form" :model="ruleForm" :rules="rules">
        <el-form-item prop="username">
          <el-input v-model="ruleForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item> 
        <el-form-item prop="password">
          <el-input v-model="ruleForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>

        <el-form-item v-if="ruleForm.type === 1" prop="rePassword">
          <el-input v-model="ruleForm.rePassword" type="password" placeholder="请再次输入密码"></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button class="sub-btn" type="primary" @click="submit"
            >{{ ruleForm.type === 0 ? '登录' : '注册' }}</el-button>
        </el-form-item>
        <div class="link">
          <span type="primary" @click="switchType()">{{ ruleForm.type === 0 ? '注册' : '登录' }}</span>
        </div>
      </el-form>

    </el-dialog>
  </div>
</template>
<script>
import { reactive,ref,toRefs } from 'vue'
import { registerApi } from '@/api/user.js'
import { useStore } from 'vuex'
export default {
  name:'Login',
  setup(){
    const store = useStore()
    
    // 校验重复密码
    const validateRePassword = (rule,value,callback)=>{
      if(value === ''){
        return callback(new Error('第二次密码不能为空'))
      }else if(value !== state.ruleForm.password){
        return callback(new Error('两次密码不同'))
      }else{
        callback()
      }
    }
    
    // 提交表单
    let state = reactive({
      ruleForm:{
        username:'',
        password:'',
        rePassword:'',
        type:0
      },
      rules:{
        username:[
          {
            required:true,
            message:'用户名不能为空',
            trigger:'blur'
          }
        ],
        password:[
          {
            required:true,
            message:'密码不能为空',
            trigger:'blur'
          }
        ],
        rePassword:[]
      }
      
    })
    
    // 默认是登录 0为登录，1是注册
    // 切换登录和注册模式
    function switchType(){
      // console.log('switchType type:',state.type)
      state.ruleForm.type = state.ruleForm.type === 0 ? 1 : 0
      // 动态添加验证规则

      if(state.ruleForm.type === 0){
        state.rules.rePassword = []
      }else {
        state.rules.rePassword = [{
          validator:validateRePassword,
          trigger:'blur'
        }]
      }
    }

    

    
    // form = toRefs(form)
    return {
      ...toRefs(state),
      switchType,
    }
  },
  methods:{
    // 登录和注册
     async submit(){
      try{
        // console.log('this.$refs.form.validate:',this.$refs.form.validate)
        this.$refs.form.validate(async (validResult)=>{
         if(validResult){
            // 登录
            if(this.ruleForm.type === 0){

              let result = await this.$store.dispatch('user/login',this.ruleForm)
              if(result.code === 0){
                this.$router.push({path:'/index'})
              }
            }else{
              // 注册
              const {username,password,rePassword} = this.ruleForm
              registerApi({username:username.trim(),password:password.trim(),rePassword:rePassword.trim()}).then(res=>{
                if(res.code === 0){
                  this.$message({
                    type:'success',
                    message:'注册成功，请重新登录'
                  })
                  this.$refs.form.resetFields()
                  this.ruleForm.type = 0
                  this.$router.replace({path:'/login'})
                }

              }).catch(err=>{
                // this.$message({
                //   type:'error',
                //   message: err.msg || '注册失败，请重新注册'
                // })
                // reject(err)
              })
            }
          }
        })
        
        
        
        
        
      }catch(err){
        console.log('err:',err)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.cont{
  background: url('@/assets/index/login-bg.jpg');
  width: 100%;
  height: 100%;
  background-size: contain;
  .con-dialog{
    border-right: 10rpx;
    .sub-btn{
      width: 100%;
    }
    .link{
      color:#66b1ff;
      cursor: pointer;
    }
  }
  
}
</style>
